<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/5/23 0023
 * Describe: 签名管理类.
 */

namespace app\api\controller\lishidai;

use think\Controller;

class Sign extends Controller
{
    //错误信息
    public static $error = 'error';

    /**
     * 校验签名是否正确.
     *
     * @return bool
     */
    public function isCheckSign()
    {
        if (strtolower(request()->action()) != 'waitingconfirm') {//订单等待确认的H5页面不需要验证post
            $param = input('');
            if (empty($param)) {
                self::$error = '缺少请求参数';

                return false;
            } elseif (!isset($param['ua']) || empty($param['ua'])) {
                self::$error = '缺少请求参数 ua';

                return false;
            } elseif (!isset($param['call']) || empty($param['call'])) {
                self::$error = '缺少请求参数标识 call';

                return false;
            } elseif (!isset($param['args']) || empty($param['args'])) {
                self::$error = '缺少请求参数 args';

                return false;
            } elseif (!isset($param['sign']) || empty($param['sign'])) {
                self::$error = '缺少请求参数 sign';

                return false;
            } elseif (!isset($param['timestamp']) || empty($param['timestamp'])) {
                self::$error = '缺少请求参数 timestamp';

                return false;
            }

            $lishidaiConfig = $this->getLishidaiConfig();
            $signKey = $param['ua'].$lishidaiConfig['lishidai_key'].$param['ua'];
            $sign = md5($signKey.$param['args'].$signKey);
//          if ($sign != $param['sign']) {
//              self::$error = '签名匹配错误';
//
//              return false;
//          }
        }

        return true;
    }

    /**
     * 获取错误信息.
     *
     * @return
     */
    public function getError()
    {
        return self::$error;
    }

    /**
     * 获取配置立时贷配置参数 ua key.
     *
     * @return array
     */
    public function getLishidaiConfig()
    {
        $data = db('sys_integrate')->alias('i')
            ->join('xb_sys_inteparameter in', 'i.ID = in.IntegrateID')
            ->where(['i.Status' => 1, 'i.EName' => 'lishidai'])
            ->select();

        if (!$data) {
            errorResult('未配置立时贷');
        }

        $temp = [];
        foreach ($data as $k => $v) {
            $temp[$v['ParaName']] = $v['ParaValue'];
        }

        if (!$temp || !isset($temp['lishidai_ua']) || empty($temp['lishidai_ua'])) {
            errorResult('未配置立时贷平台接入标识 ua');
        } elseif (!$temp || !isset($temp['lishidai_key']) || empty($temp['lishidai_key'])) {
            errorResult('未配置立时贷签名密钥 signkey');
        } elseif (!$temp || !isset($temp['lishidai_url']) || empty($temp['lishidai_url'])) {
            errorResult('未配置立时贷 url');
        }

        return $temp;
    }
}
